package com.jhm.bing_fa_rong_qi;

import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

import java.util.Comparator;

public class PriorityBlockingQueueExample {
    public static void main(String[] args) throws InterruptedException {
        // 创建一个自然排序的PriorityBlockingQueue
        BlockingQueue<Integer> queue = new PriorityBlockingQueue<>(10,Integer::compareTo);

        // 添加元素
        queue.add(5);
        queue.add(1);
        queue.add(3);
        queue.add(4);
        queue.add(2);

        // 消费者线程
        Thread consumer = new Thread(() -> {
            try {
                // 取出并消费元素
                System.out.println("Consuming: " + queue.take());
                System.out.println("Consuming: " + queue.take());
                System.out.println("Consuming: " + queue.take());
                System.out.println("Consuming: " + queue.take());
                System.out.println("Consuming: " + queue.take());
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        consumer.start();

        // 给消费者线程一点时间来启动
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        // 生产者线程
        Thread producer = new Thread(() -> {
            try {
                // 在消费者消费一些元素后添加新元素
                queue.add(0);
                queue.add(6);
            } catch (Exception e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        Thread.sleep(1000);
        System.out.println(queue.size());
    }
}